package com.cooge.statistics.common.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cooge.statistics.common.model.MainMenu;
import com.cooge.statistics.common.model.SystemSet;
import com.cooge.statistics.common.model.UserInfo;
import com.cooge.statistics.common.service.MainMenuService;
import com.cooge.statistics.common.service.UserInfoService;
import com.cooge.statistics.common.util.URLUtil;
@Controller
@RequestMapping("system")
public class SystemController {
	
	@Autowired
	UserInfoService userInfoService;
	@Autowired
	MainMenuService mainMenuService;
	
	@RequestMapping(value = "json/set", method = RequestMethod.GET)
	@ResponseBody
	public String set(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HttpSession session = request.getSession();
		SystemSet systemSet = ((SystemSet)session.getAttribute(URLUtil.SYSTEMSET));
		UserInfo ui = ((UserInfo)session.getAttribute(URLUtil.UID));
		String theme =  request.getParameter(URLUtil.THEME);
		if(theme!=null&&(!theme.trim().equals(""))){
			systemSet.setTheme(theme);
		}
		if(userInfoService.updateSystemset(ui.getId(), JSON.toJSONString(systemSet))){
			return URLUtil.SUCCESS;
		}else{
			return URLUtil.ERROR;
		}
	}
	
	@RequestMapping(value = "json/session", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String session(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		HttpSession session = request.getSession(false);
		String str = "";
		if(session==null){
			str = "time out";
		}else{
			str  = String.valueOf(session.getLastAccessedTime());
		}
		return JSON.toJSONString(str);
	}
	
	@RequestMapping(value = "json/cn", method = RequestMethod.GET)
	public String cn(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "cn";
	}
	
	@RequestMapping(value = "menuManager", method = RequestMethod.GET)
	public String menuManager(ModelMap map,HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		List<MainMenu>  mlist = mainMenuService.findByNOSMList(new String[]{"id","pid","title"});
		String str = JSON.toJSONString(mlist);
		map.addAttribute("menulist", str);
		return "menu/index";
	}
	
	
}
